package com.xulu.romance.handler;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.xulu.romance.constants.Constant;
import com.xulu.romance.exception.RomanceException;
import com.xulu.romance.pojo.User;
import com.xulu.romance.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class InterceptorHandler implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println("Request URI: " + request.getRequestURI());

        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        if (StringUtils.isBlank(token)){
            throw new RomanceException(Constant.FAILURE_TOKEN,"无Token,请重新登录");
        }

        String userId;
        try {
            userId= JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new RomanceException(Constant.FAILURE_TOKEN,"token验证失败");
        }

        User user = userService.getById(userId);
        if (user==null){
            throw new RomanceException(Constant.FAILURE_TOKEN,"用户不存在,请重新登录");
        }

        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(Constant.SIGNATURE)).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new RomanceException(Constant.FAILURE_TOKEN,"token验证失败,请重新登录");

        }


        return true;
    }
}
